// src/main/java/tech/aistar/mapper/AfterSaleMapper.java
package tech.aistar.mapper;

import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import tech.aistar.pojo.AfterSale;
import java.util.List;
import java.util.Map;

@Mapper
public interface AfterSaleMapper {

    /** 根据售后服务id查找 */
    @Select("select * from after_sale where after_sale_id = #{afterSaleId}")
    AfterSale getById(Integer afterSaleId);

    /** 根据售后服务id进行删除 */
    @Delete("delete from after_sale where after_sale_id = #{afterSaleId}")
    int deleteById(Integer afterSaleId);

    /** 增加一条售后服务 - 修复：添加create_time字段 */
    @Insert("insert into after_sale(order_id, user_id, type, reason, status, create_time, process_time) " +
            "values(#{orderId}, #{userId}, #{type}, #{reason}, #{status}, #{createTime}, #{processTime})")
    @Options(useGeneratedKeys = true, keyProperty = "afterSaleId")
    int addAfterSale(AfterSale afterSale);

    /** 修改售后服务 */
    @Update("update after_sale set order_id=#{orderId}, user_id=#{userId}, type=#{type}, " +
            "reason=#{reason}, status=#{status}, process_time=#{processTime} " +
            "where after_sale_id=#{afterSaleId}")
    int updateAfterSale(AfterSale afterSale);

    /** 根据用户ID查询售后列表 */
    @Select("select * from after_sale where user_id = #{userId} order by create_time desc")
    List<AfterSale> getByUserId(Integer userId);

    /** 查询所有售后申请 */
    @Select("select * from after_sale order by create_time desc")
    List<AfterSale> getAll();

    // 新增：分页查询售后列表（关联用户表获取买家信息）
    @SelectProvider(type = AfterSaleSqlProvider.class, method = "selectAfterSaleList")
    List<AfterSale> selectAfterSaleList(@Param("orderId") String orderId,
                                        @Param("buyerName") String buyerName,
                                        @Param("type") Integer type,
                                        @Param("status") Integer status,
                                        @Param("offset") Integer offset,
                                        @Param("size") Integer size);

    // 新增：查询售后总数
    @SelectProvider(type = AfterSaleSqlProvider.class, method = "countAfterSales")
    Long countAfterSales(@Param("orderId") String orderId,
                         @Param("buyerName") String buyerName,
                         @Param("type") Integer type,
                         @Param("status") Integer status);

    // 新增：更新售后状态
    @Update("UPDATE after_sale SET status = #{status}, process_time = NOW() WHERE after_sale_id = #{afterSaleId}")
    int updateStatus(@Param("afterSaleId") Integer afterSaleId, @Param("status") Integer status);

    // 创建 SQL 提供者类
    class AfterSaleSqlProvider {
        public String selectAfterSaleList(Map<String, Object> params) {
            return new SQL() {{
                SELECT("a.*, u.username as buyer_name");
                FROM("after_sale a");
                LEFT_OUTER_JOIN("user u ON a.user_id = u.id");
                WHERE("1=1");
                if (params.get("orderId") != null && !params.get("orderId").toString().isEmpty()) {
                    AND().WHERE("a.order_id LIKE CONCAT('%', #{orderId}, '%')");
                }
                if (params.get("buyerName") != null && !params.get("buyerName").toString().isEmpty()) {
                    AND().WHERE("u.username LIKE CONCAT('%', #{buyerName}, '%')");
                }
                if (params.get("type") != null) {
                    AND().WHERE("a.type = #{type}");
                }
                if (params.get("status") != null) {
                    AND().WHERE("a.status = #{status}");
                }
                ORDER_BY("a.create_time DESC");
            }}.toString() + " LIMIT #{offset}, #{size}";
        }

        public String countAfterSales(Map<String, Object> params) {
            return new SQL() {{
                SELECT("COUNT(*)");
                FROM("after_sale a");
                LEFT_OUTER_JOIN("user u ON a.user_id = u.id");
                WHERE("1=1");
                if (params.get("orderId") != null && !params.get("orderId").toString().isEmpty()) {
                    AND().WHERE("a.order_id LIKE CONCAT('%', #{orderId}, '%')");
                }
                if (params.get("buyerName") != null && !params.get("buyerName").toString().isEmpty()) {
                    AND().WHERE("u.username LIKE CONCAT('%', #{buyerName}, '%')");
                }
                if (params.get("type") != null) {
                    AND().WHERE("a.type = #{type}");
                }
                if (params.get("status") != null) {
                    AND().WHERE("a.status = #{status}");
                }
            }}.toString();
        }
    }
}